/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.tutwiz.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import net.tutwiz.model.Vote;


/**
 *
 * @author vind
 */
public class VotePersistenceManager implements IPersistenceManager<Vote> {

//    @PersistenceContext(unitName = "TutWizPU")
    private EntityManager em;

    public VotePersistenceManager() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TutWizPU");
        em = emf.createEntityManager();
    }
    
    public VotePersistenceManager(boolean testing){
        em = Persistence.createEntityManagerFactory("TutwizTestPU").createEntityManager();
    }
    
    @Override
    public void save(Vote v) {
        em.getTransaction().begin();
        em.persist(v);
        em.getTransaction().commit();
    }

    @Override
    public void delete(Vote v) {
        em.getTransaction().begin();
        em.remove(v);
        em.getTransaction().commit();
    }

    @Override
    public void update(Vote v) {
        em.getTransaction().begin();
        em.merge(v);
        em.getTransaction().commit();
    }

    @Override
    public Vote get(Long id) {
        return em.find(Vote.class, id);
    }

    @Override
    public List<Vote> getAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Vote.class));
        return em.createQuery(cq).getResultList();
    }

    @Override
    public int count() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<Vote> rt = cq.from(Vote.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

    @Override
    public EntityManager getEntityManager() {
        return em;
    }

    @Override
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    
}
